import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tracker/common/enums/user_type_enum.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/home/home/model/home_device_info_resp.dart';
import 'package:tracker/pages/home/home/model/user_info_resp.dart';
import 'package:tracker/pages/profile/model/customer_service_info_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/startup/env/env.dart';
import 'package:device_info_plus/device_info_plus.dart';

import '../../../theme/app_theme.dart';

/// 客服页面
class CustomerServicePage extends ConsumerStatefulWidget {
  const CustomerServicePage({super.key});

  @override
  ConsumerState<CustomerServicePage> createState() => _CustomerServicePageState();
}

class _CustomerServicePageState extends ConsumerState<CustomerServicePage> {
  String title = '客服';

  final GlobalKey webViewKey = GlobalKey();
  InAppWebViewController? webViewController;

  InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
    crossPlatform: InAppWebViewOptions(
      useShouldOverrideUrlLoading: true,
      mediaPlaybackRequiresUserGesture: false,
      minimumFontSize: 17,
      // 是否缓存
      // cacheEnabled: false,
      // clearCache: true,
    ),
    android: AndroidInAppWebViewOptions(
      useHybridComposition: true,
    ),
    ios: IOSInAppWebViewOptions(
      allowsInlineMediaPlayback: true,
    ),
  );

  _fetchCustomerServiceInfo() async {
    UserInfoData userInfo = ref.read(userInfoProvider);
    DeviceInfoVO deviceInfo = ref.read(deviceInfoProvider);
    // 登录方式
    var loginTypeEnum = UserTypeEnum.fromValue(userInfo.type!);
    var loginType = loginTypeEnum.value;
    // 登录账号
    var loginAccount = userInfo.nickname;
    if (loginTypeEnum == UserTypeEnum.phone) {
      loginAccount = userInfo.phone;
    } else if (loginTypeEnum == UserTypeEnum.device) {
      loginAccount = deviceInfo.imei;
    } else if (loginTypeEnum == UserTypeEnum.agent) {
      loginAccount = userInfo.nickname;
    }
    // 客户端
    var appName = Env.envConfig.appName + 'App';
    // 系统信息
    DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
    var systemInfo = '';
    if (Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await deviceInfoPlugin.androidInfo;
      systemInfo = 'Android ${androidInfo.version.release}';
    } else if (Platform.isIOS) {
      IosDeviceInfo iosInfo = await deviceInfoPlugin.iosInfo;
      systemInfo = 'iOS ${iosInfo.systemVersion}';
    }
    XLogger.info('登录方式: $loginType, 登录账号: $loginAccount, 客户端: $appName, 系统信息: $systemInfo');

    final res = await post<CustomerServiceInfoResp, CustomerServiceInfoResp>('/config/customerServiceInfo',
        data: {'imei': deviceInfo.imei}, decodeType: CustomerServiceInfoResp());
    res.when(success: (resp) {
      if (resp.code == 200) {
        // url编码
        var url = Uri.encodeFull(resp.data!.url!);
        var uri = Uri.parse(url);
        Map<String, String> queryParameters = Map<String, String>.from(uri.queryParameters);
        var businessParam = queryParameters['businessParam'];
        businessParam =
            '${businessParam},loginType:$loginType,loginAccount:$loginAccount,client:$appName,systemInfo:$systemInfo';
        queryParameters['businessParam'] = businessParam;
        final newUrl = uri.replace(queryParameters: queryParameters);
        XLogger.info('客服链接: $newUrl');
        webViewController?.loadUrl(urlRequest: URLRequest(url: newUrl));
      }
    }, failure: (String msg, int code) {
      XLogger.error('获取客服信息失败 code: $code msg: $msg');
    });
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 在build执行完成后回调
      _fetchCustomerServiceInfo();
    });
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title, style: const TextStyle(color: Colors.white)),
        centerTitle: true,
        backgroundColor: AppTheme.themeConfig.primaryColor,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: InAppWebView(
        key: webViewKey,
        initialOptions: options,
        onWebViewCreated: (controller) {
          webViewController = controller;
        },
        onTitleChanged: (controller, newTitle) {
          setState(() {
            title = newTitle ?? '';
          });
        },
      ),
    );
  }
}
